<?php

namespace App\Services\Admin\V1;

use App\Models\V1\Menu;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Collection;
use App\Http\Requests\Admin\V1\MenuStoreRequest;
use App\Http\Requests\Admin\V1\MenuUpdateRequest;

class MenuService
{
    /**
     * @expalin GET ALL MENUS
     * @return Collection
     * @method
     * @author 陈文小超
     * @maxim from专注to执行
     * @time 2021/4/1/11:03
     */
    public function all(): Collection
    {
        return Menu::get();
    }

    /**
     * @expalin GET MENUS BY ID
     * @param int $id
     * @return Menu
     * @method
     * @author 陈文小超
     * @maxim from专注to执行
     * @time 2021/4/1/11:18
     */
    public function find(int $id): Menu
    {
        return Menu::findOrFail($id);
    }

    /**
     * @expalin CREATE MENU
     * @param MenuStoreRequest $request
     * @return Menu
     * @method
     * @author 陈文小超
     * @maxim from专注to执行
     * @time 2021/4/1/11:24
     */
    public function store(MenuStoreRequest $request): Menu
    {
        $menu = new Menu();
        $menu->parent_id = (int) $request->input('parent_id');
        $menu->name = $request->input('name') ?? '';
        $menu->title = $request->input('title') ?? '';
        $menu->icon = $request->input('icon') ?? '';
        $menu->path = $request->input('path') ?? '';
        $menu->component_path = $request->input('component_path') ?? '';
        $menu->is_enable = $request->input('is_enable') ? Menu::ENABLE_TRUE : Menu::ENABLE_FALSE;
        $menu->save();

        return $menu;
    }

    /**
     * @expalin UPDATE MENU
     * @param int $id
     * @param MenuUpdateRequest $request
     * @return Menu
     * @method
     * @author 陈文小超
     * @maxim from专注to执行
     * @time 2021/4/1/11:34
     */
    public function update(int $id, MenuUpdateRequest $request): Menu
    {
        $menu = $this->find($id);
        $menu->parent_id = (int) $request->input('parent_id');
        $menu->name = $request->input('name') ?? '';
        $menu->title = $request->input('title') ?? '';
        $menu->icon = $request->input('icon') ?? '';
        $menu->path = $request->input('path') ?? '';
        $menu->component_path = $request->input('component_path') ?? '';
        $menu->is_enable = $request->input('is_enable') ? Menu::ENABLE_TRUE : Menu::ENABLE_FALSE;
        $menu->save();

        return $menu;
    }

    /**
     * @expalin DELETE MENU BY ID
     * @param Menu $menu
     * @return bool
     * @method
     * @author 陈文小超
     * @maxim from专注to执行
     * @time 2021/4/1/11:44
     */
    public function destroy(Menu $menu): bool
    {
        $children = Menu::where('parent_id', $menu->id)->enable()->count();

        if ($children) {
            return false;
        }

        DB::transaction(function () use ($menu) {
            // 删除关联角色
            $menu->roles()->detach();

            $menu->delete();
        });

        return true;
    }
}
